const app = getApp();
Component({
  properties: {
    receiveData: {
      type: Object,
      value: 'default value',
    },
    params: {
      type: Object,
      value: {},
    },
    reqType: {
      type: Object,
      value: '',
    },
  },
  data: {
    setting: null, 
    servantList: [], 
    sysWidth: 320,
    positionTab: '',
    servantShowWay: 2, 
    localPoint: { longitude: '0', latitude: '0' },
    organizesDetail: null,
    limitState: 0,
    markers: [{
      iconPath: "../../images/icon/mapItem.png",
      id: 0,
      width: 20,
      heigth: 20,
      latitude: 26.060701172100124,
      longitude: 119.30130341796878,
    }],
    /* 全部参数 */
    params: {
      name: "",
      addressStr: "",
      page: 1,
      latitude: '0',
      longitude: '0',
    },
    listPage: {
      page: 1,
      pageSize: 0,
      totalSize: 0,
      curpage: 1
    },
  },
  ready: function () {
    let that = this;
    console.log("====servant-data=====", that.data.receiveData);
    if (that.data.receiveData.jsonData && that.data.receiveData.jsonData.count) {
      that.setData({ limitState: that.data.receiveData.jsonData.count })
    }
    console.log("====servant-limitState=====", that.data.limitState)
    console.log("====servant-params=====", that.data.params)
    let options = that.data.receiveData;
    that.initSetting();
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        that.data.localPoint.latitude = res.latitude
        that.data.localPoint.longitude = res.longitude
        that.data.params.latitude = res.latitude
        that.data.params.longitude = res.longitude
        console.log("options", options)
        if (options.servantTypeId) {
          that.setData({ positionTab: options.servantTypeId })
          options.categoryId = options.servantTypeId
          that.bindTypeItem(options.servantTypeId)
        }
        if (!!options.forceSearch && options.forceSearch == 2) {
          that.setData({ OrganizeshowWay: 2 })
        } else {
          that.setData({ OrganizeshowWay: 2 })
        }
        for (let i in options) {
          for (let j in that.data.params) {
            if (i.toLowerCase() == j.toLowerCase()) { that.data.params[j] = options[i] }
          }
        }
        that.setData({
          params: that.data.params,
          localPoint: that.data.localPoint
        })
        console.log(that.data.params)
        that.getData(that.data.params);
      }
    })
  },
  methods: {
    calling: function (e) {
      console.log('====e===', e)
      let phoneNumber = e.currentTarget.dataset.phonenumber
      wx.makePhoneCall({
        phoneNumber: phoneNumber, //此号码并非真实电话号码，仅用于测试
        success: function () {
          console.log("拨打电话成功！")
        },
        fail: function () {
          console.log("拨打电话失败！")
        }
      })
    },
    toIndex() {
      app.globalData.toIndex()
    },
    clickcontrol(e) {
      let mpCtx = wx.createMapContext("map");
      mpCtx.moveToLocation();
    },
    getCenterPoint(callback) {
      let that = this;
      var mapCtx = wx.createMapContext('map')
      mapCtx.getCenterLocation({
        success: function (res) {
          console.log('res', res)
          that.data.params.latitude = res.latitude;
          that.data.params.longitude = res.longitude;
          that.setData({
            params: that.data.params,
          })
          if (callback) {
            callback
          }
        }
      })
    },
    regionchange(e) {
      console.log('===regionchange===', e)
      if (e.type == 'end') {
        if (e.causedBy == 'scale') {
          console.log('====scale====')
        } else if (e.causedBy == 'drag') {
          console.log('====drag====');
          this.getCenterPoint(this.getData(this.data.params));
        } else {
          console.log('====all====');
          this.getCenterPoint(this.getData(this.data.params));
        }
      }
    },
    markertap(e) {
      console.log(e.markerId)
      // this.toOrganizesDetailMap(e.markerId);
    },
    controltap(e) {
      console.log(e)
    },
    hiddenProInfo(e) {
      console.log(e)
      this.setData({ servantDetail: null })
    },
    /* 获取数据 */
    getData: function (param) {
      var that = this
      let params=Object.assign({},param,{
          pageObjectId: that.data.receiveData.pageObjectId||0,
          pageObjectType: that.data.receiveData.pageObjectType||0
      })
      let la1 = that.data.localPoint.latitude
      let lo1 = that.data.localPoint.longitude
      var customIndex = app.globalData.AddClientUrl("/wx_find_servants.html", params)
      app.globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log("===getData===",res.data)
          that.data.listPage.pageSize = res.data.relateObj.pageSize
          that.data.listPage.curPage = res.data.relateObj.curPage
          that.data.listPage.totalSize = res.data.relateObj.totalSize
          let dataArr = that.data.servantList
          let tagArray = [];
          if (param.page == 1) {
            dataArr = []
          }
          if (!res.data.relateObj.result || res.data.relateObj.result.length == 0) {
            that.setData({ servantList: null })
          } else {
            if (dataArr == null) { dataArr = [] }
            dataArr = dataArr.concat(res.data.relateObj.result)
            for (let i = 0; i < dataArr.length; i++) {
              dataArr[i].pingfenStr= dataArr[i].pingfen.toFixed(1);
              if (dataArr[i].tags && dataArr[i].tags != '') {
                tagArray = dataArr[i].tags.slice(1, -1).split("][")
                dataArr[i].tagArray = tagArray;
              }
            }
            for (let i = 0; i < dataArr.length; i++) {
              if (dataArr[i].latitude && dataArr[i].latitude != 0 && dataArr[i].longitude && dataArr[i].longitude != 0) {
                dataArr[i].distance = app.globalData.getDistance(la1, lo1, dataArr[i].latitude, dataArr[i].longitude)
              }
            }
            if(that.data.limitState>0){
                dataArr=dataArr.slice(0,that.data.limitState)
            }
            that.setData({ servantList: dataArr })
          }
          that.setData({ markers: that.data.servantList })
          let conut = 0;
          if (that.data.markers) {
            for (let i = 0; i < that.data.markers.length; i++) {
              if (that.data.markers[i].categoryIcon) {
                that.downProIcon(that.data.markers[i].categoryIcon, function (url) {
                  conut++;
                  that.data.markers[i].iconPath = url;
                  that.data.markers[i].width = 32;
                  that.data.markers[i].height = 32;
                  if (conut == that.data.markers.length) {
                    that.setData({ markers: that.data.markers })
                    console.log('==that.data.markersHave===', that.data.markers);
                  }
                })
              } else {
                conut++;
                that.data.markers[i].iconPath = '../../images/icon/mapItem.png';
                that.data.markers[i].width = 32;
                that.data.markers[i].height = 32;
                if (conut == that.data.markers.length) {
                  that.setData({ markers: that.data.markers })
                  console.log('==that.data.markers===', that.data.markers);
                }
              }

            }
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    downProIcon: function (url, callback) {
      var _this = this;
      if (app.globalData.mapProIconArray[encodeURIComponent(url)]) {
        console.log('已存在', encodeURIComponent(url))
        callback(app.globalData.mapProIconArray[encodeURIComponent(url)])
        return
      }
      wx.downloadFile({
        url: url.replace('http', 'https'),
        success: function (res) {
          console.log('下载图片', res)
          if (res.statusCode == 200) {
            callback(res.tempFilePath);
            app.globalData.mapProIconArray[encodeURIComponent(url)] = res.tempFilePath
          }
        }
      })
    },
    /* 查找商品 */
    getSearchName: function (params) {
      console.log("====getSearchName====", params)
      var that = this
      that.getData(params)
    },
    tolinkUrl: function (e) {
      let linkUrl = e.currentTarget.dataset.link
      app.globalData.linkEvent(linkUrl)
    },
    clickEventFun:function(e){
        let that=this;
        console.log("===clickEventFun===",e)
        if(that.reqType=='order'){
            that.selectItem(e)
        }else{
            that.tolinkUrl(e)
        }
    },
    selectItem: function (e) {
      console.log("订单选择服务人员",e);
      let pages = getCurrentPages(); //当前页面
      console.log("==pages===",pages)
      this.triggerEvent('closePoaster', 0)
      let selectServant=e.currentTarget.dataset.info
      let prevPage = pages[pages.length - 2]; //上一页面
      console.log("==prevPage===",prevPage)
      prevPage.setData({
        //直接给上移页面赋值
        selectServant: selectServant
      });
      wx.navigateBack();
    },
    initSetting() {
      this.setData({ setting: app.globalData.setting })
      for (let i = 0; i < this.data.setting.platformSetting.categories.length; i++) {
        this.data.setting.platformSetting.categories[i].colorAtive = '#888';
      }
      this.data.setting.platformSetting.categories[0].colorAtive = this.data.setting.platformSetting.defaultColor;
      this.setData({
        setting: this.data.setting,
      })
    },
    pullDownRefreshFun: function () {
      this.data.params.name = ""
      this.data.listPage.page = 1
      this.data.params.page = 1
      this.getData(this.data.params)

    },
    reachBottomFun: function () {
      var that = this
      if (that.data.listPage.totalSize > that.data.listPage.curPage * that.data.listPage.pageSize) {
        that.data.listPage.page++
        that.data.params.page++
        that.getData(that.data.params);
      }
    },
  }
})